package cn.jsu.oj.judgment.process.Handle;

import cn.jsu.oj.judgment.pojo.AbstractPack;
import cn.jsu.oj.judgment.pojo.JudgeResult;
import cn.jsu.oj.judgment.pojo.SendBoxApply;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import static cn.jsu.oj.judgment.config.DataStructureConfig.judgeResultQueue;
import static cn.jsu.oj.judgment.config.DataStructureConfig.sendBoxApplyQueue;

/**
 * 判题机 Unix套接域服务通道处理器
 */
@Slf4j
@ChannelHandler.Sharable
public class JudgeUnixDomainHandler extends ChannelInboundHandlerAdapter {

    /**
     * 沙箱通道
     */
    public static Channel channel;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("..........判题机沙箱进程以建立连接.......");
        channel = ctx.channel();
        super.channelActive(ctx);
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        AbstractPack abstractPack = (AbstractPack) msg;
        short typeNo = abstractPack.getTypeNo();
        //如果是判题结果
        if (typeNo == 8) {
            judgeResultQueue.put(((JudgeResult) abstractPack));
        }
        //如果是判题机申请信息
        else if (typeNo == 13) {
            sendBoxApplyQueue.put((SendBoxApply) abstractPack);
        }
        super.channelRead(ctx, msg);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().close();
        super.channelInactive(ctx);
    }
}
